package com.biostime.springdraw.modules.sd.web;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.biostime.springdraw.common.api.FastResponse;
import com.biostime.springdraw.common.api.ObjResponse;
import com.biostime.springdraw.common.config.Global;
import com.biostime.springdraw.common.utils.StringUtils;
import com.biostime.springdraw.common.web.BaseController;
import com.biostime.springdraw.common.wechat.BiostimeWechat;
import com.biostime.springdraw.common.wechat.Mama100Wechat;
import com.biostime.springdraw.modules.sd.dto.DrawDto;
import com.biostime.springdraw.modules.sd.dto.WinnerDto;
import com.biostime.springdraw.modules.sd.entity.Member;
import com.biostime.springdraw.modules.sd.entity.Share;
import com.biostime.springdraw.modules.sd.entity.Sharegrid;
import com.biostime.springdraw.modules.sd.entity.Subscriber;
import com.biostime.springdraw.modules.sd.entity.Winner;
import com.biostime.springdraw.modules.sd.service.CreateSignService;
import com.biostime.springdraw.modules.sd.service.DrawService;
import com.biostime.springdraw.modules.sd.service.HttpRequestService;
import com.biostime.springdraw.modules.sd.service.JssdkService;
import com.biostime.springdraw.modules.sd.service.MemberService;
import com.biostime.springdraw.modules.sd.service.ShareService;
import com.biostime.springdraw.modules.sd.service.ShareawardService;
import com.biostime.springdraw.modules.sd.service.SharegridService;
import com.biostime.springdraw.modules.sd.service.SignService;
import com.biostime.springdraw.modules.sd.service.SubscriberService;
import com.biostime.springdraw.modules.sd.service.WinnerService;
import com.biostime.springdraw.modules.sys.entity.User;
import com.github.pagehelper.PageHelper;

/**
 * 前端控制器Controller
 * @author Phil
 * @version 2016-01-19
 */
@Controller
@RequestMapping(value = "/")
public class FrontController extends BaseController {
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private DrawService drawService;
	
	@Autowired
	private WinnerService winnerService;
	
	@Autowired
	private SharegridService sharegridService;
	
	@Autowired
	private ShareawardService shareawardService;
	
	@Autowired
	private ShareService shareService;
	
	@Autowired
	private JssdkService jssdkService;
	
	@Autowired
	private SubscriberService subscriberService;
		
	@RequestMapping(value = "front")
	public String index(@RequestParam(required = false) String openId,@RequestParam(required = false) String openid, HttpServletRequest request, HttpServletResponse response, Model model) {
		 String fromSystem = null;
		try {
			
			String msg = null;
			int drawTimes = 0;
			if(openid != null && !openid.equals("")){
				openId = openid;
			}
								
	        fromSystem = request.getParameter("fromSystem");
	        
			//判断是否有openId
			if(StringUtils.isEmpty(openId)){

				String url = "http://"+Global.getConfig("serverurl")+"/front"+getRequestUrl2(request);
								
				String authUrl = null;
											
/*				//从妈妈100进来的，附带参数fromSystem=mama100
				if(fromSystem != null && "mama100".equals(fromSystem)){								
					authUrl = "http://"+Global.getConfig("biostime.wxhost")+"/bncweixin/service/authorize?encodeTargetUrl="+URLEncoder.encode(url,"utf-8")+
							"&fromSystem=mama100";				
				}
				
				//从合生元进来的
				else{
					authUrl = "http://"+Global.getConfig("biostime.wxhost")+"/bncweixin/service/authorize?encodeTargetUrl="+URLEncoder.encode(url,"utf-8");
				}*/
				
				authUrl = "http://"+Global.getConfig("biostime.wxhost")+"/bncweixin/service/authorize?encodeTargetUrl="+URLEncoder.encode(url,"utf-8")+
						"&fromSystem=mama100";		
										
				return "redirect:"+authUrl;
			}			
					
			//查询是否存在用户信息
			Member member = memberService.getByOpenId(openId);
			Map<String,String> ret = BiostimeWechat.Api.getCustomerInfo(openId);
			if(member==null){
										
				if(ret!=null){
					
					String code = ret.get("code");
					if(code==null || !code.equals("100")){
						String registerUrl = null;
/*						if(fromSystem != null && "mama100".equals(fromSystem)){							
							return "redirect:"+Global.getConfig("mama100Register");
						}else{
							registerUrl = "http://"+Global.getConfig("serverurl")+"/bncweixin/html5/register.html?url="+URLEncoder.encode(getRequestUrl(request),"utf-8");
							return "redirect:"+registerUrl;
						}
						registerUrl = "http://"+Global.getConfig("biostime.wxhost")+"/bncweixin/html5/register.html?url="+URLEncoder.encode(url,"utf-8");*/
						
						String url = "http://"+Global.getConfig("serverurl")+"/front"+getRequestUrl2(request);
						registerUrl = "http://"+Global.getConfig("mama100Host")+"/weixin/bind/auth?token="+URLEncoder.encode(openId,"utf-8")
							+"&redirect="+URLEncoder.encode(url,"utf-8");
						return "redirect:"+registerUrl;
					}else{
						Member m = new Member();
						m.setOpenid(openId);
						m.setCustomerid(ret.get("customerId"));	
						m.setMobile(ret.get("mobile"));  
						m.setCreateBy(new User("0"));
						m.setCreateDate(new Date());
						m.setUpdateBy(new User("0"));
						m.setUpdateDate(new Date());			
						m.setNickname(ret.get("nickName"));  
						memberService.save(m);
					}
				}
			}
			
			//更新用户信息
			else{
				member.setNickname(ret.get("nickName")); 
				member.setMobile(ret.get("mobile")); 
				memberService.save(member); 
			}

			//抽奖次数
			Map<String,String> ret2 = BiostimeWechat.Api.queryTimes(openId);
			if(ret2==null){
				msg = "获取用户抽奖次数接口响应为空";
			}else{
				String code = ret2.get("code");
				if(code==null || !code.equals("100")){
					msg = ret2.get("desc");
				}else{
					drawTimes = StringUtils.toInteger(ret2.get("drawTimes"));
				}
			}
			
			//通过openid获取微信用户信息
			Subscriber sub = subscriberService.getByOpenid(openId);
			if(sub == null){
				if(openId != null){
					Map<String,Object> map = Mama100Wechat.Api.getWechatInfo(openId);
					String nickName = map.get("nickName").toString();
					String headImgUrl = map.get("headImgUrl").toString();
					Subscriber subscriber = new Subscriber();
					subscriber.setOpenid(openId); 
					subscriber.setNickname(nickName);
					subscriber.setHeadimgurl(headImgUrl);
					subscriberService.save(subscriber); 
				}					
			}
						
			String url =  "http://"+Global.getConfig("serverurl") +"/front"+getRequestUrl2(request);						
			byte[] sendBytes1 = HttpRequestService.sendGet(BiostimeWechat.Jsticket, "from=ismart");
			byte[] sendBytes2 = HttpRequestService.sendGet(BiostimeWechat.AppID, "from=ismart");
			
			String jsticketJson=new String( sendBytes1 ,"UTF-8"); 
			String appIdJson=new String( sendBytes2 ,"UTF-8"); 							
			
			HashMap<String,String> m = (HashMap<String, String>) BiostimeWechat.Api.toMap(jsticketJson);							
			String jsticket = m.get("jsticket");
			
			m = (HashMap<String, String>) BiostimeWechat.Api.toMap(appIdJson);										
			String appId = m.get("appId");			
										
			HashMap<String,String> map = (HashMap<String, String>) CreateSignService.sign(jsticket, url);
			map.put("appId", appId);
			map.put("url",url);
			model.addAttribute("map", map);			
			
			
			model.addAttribute("message", msg);
			model.addAttribute("drawTimes", drawTimes);
			model.addAttribute("openid", openId);
			model.addAttribute("url",  "http://"+Global.getConfig("serverurl") +"/front?fromSystem="+fromSystem);
			model.addAttribute("fromSystem", fromSystem);
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "modules/front/index2";
	}
	
	@ResponseBody
	@RequestMapping(value = {"${frontPath}/draw"}, method = RequestMethod.POST)
	public Object draw(@RequestParam(name="openid") String openId, HttpServletRequest request, HttpServletResponse response, Model model) {
		DrawDto drawDto = null;
		String fromSystem = request.getParameter("fromSystem");
		int errCode = 0;
		int remain = 0;
		String errMsg = "抽奖成功";
		
		try{
			drawDto = drawService.mainDraw(openId,fromSystem);
			
			Map<String,String> ret = BiostimeWechat.Api.queryTimes(openId);
			if(ret.get("drawTimes") != null){
				remain = Integer.parseInt(ret.get("drawTimes"));
			}
			drawDto.setRemain(remain); 
		}catch(Exception ex){
			errCode = 1;
			errMsg = ex.getMessage();
		}
		
		ObjResponse<DrawDto> res = FastResponse
									.create()
									.errCode(errCode)
									.errMsg(errMsg)
									.obj(drawDto);
		return res;
	}
	
	@RequestMapping(value = {"${frontPath}/winner"})
	public String winner(@RequestParam(name="openid") String openId, int pageindex,int pagesize, HttpServletRequest request, 
			HttpServletResponse response,Model model) {
		PageHelper.startPage(pageindex, pagesize);
		List<WinnerDto> winnerList = winnerService.getAllWinner(openId);
		model.addAttribute("winnerList", winnerList);
		model.addAttribute("pageindex", pageindex);
		model.addAttribute("pagesize", pagesize);
		model.addAttribute("openId", openId);
		return "modules/front/winner";
	}
	
	@RequestMapping(value = {"${frontPath}/getWinner"})
	public @ResponseBody List<WinnerDto> getWinner(@RequestParam(name="openid") String openId, int pageindex,int pagesize, HttpServletRequest request, 
			HttpServletResponse response) {
		PageHelper.startPage(pageindex, pagesize);
		List<WinnerDto> winnerList = winnerService.getAllWinner(openId);
		return winnerList;
	}	
	
	@RequestMapping(value = {"${frontPath}/rule"})
	public String rule(HttpServletRequest request, HttpServletResponse response, Model model) {		
		return "modules/front/rule2";
	}
	
	@RequestMapping(value = {"${frontPath}/contactInformation"})
	public String winner(HttpServletRequest request, HttpServletResponse response, Model model) {
		String winnerid = request.getParameter("winnerid");
		String openid = request.getParameter("openid");
		String awardname = request.getParameter("awardname");
		String fromSystem = request.getParameter("fromSystem");
		
		model.addAttribute("winnerid", winnerid);
		model.addAttribute("openid", openid);
		model.addAttribute("awardname", awardname);
		model.addAttribute("fromSystem", fromSystem);
		
		//生产签名
		String mySign = null;
        SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();  
        Winner w = winnerService.get(winnerid);
        parameters.put("winnerid", winnerid);  
        parameters.put("datetime", w.getCreateDate().getTime());  
        String characterEncoding = "UTF-8";  
        mySign = SignService.createSign(characterEncoding,parameters);	
        model.addAttribute("sign", mySign);
        
		return "modules/front/contactInformation2";
	}	

	@RequestMapping(value = {"${frontPath}/updateWinner"})	
	public String updateWinner(Winner winner,String winnerid,HttpServletRequest request, HttpServletResponse response, Model model){
		
		//校验签名
        SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();  
        Winner w = winnerService.get(winnerid);
        parameters.put("winnerid", winnerid);  
        parameters.put("datetime", w.getCreateDate().getTime());  
        String characterEncoding = "UTF-8";          
        String  sign = SignService.createSign(characterEncoding,parameters);	
                
        if(sign.equals(request.getParameter("sign"))){
        	
        	logger.info(request.getParameter("fromSystem")); 
        	winner.setRecAddr(request.getParameter("recAddr1")+request.getParameter("recAddr2"));
        	
        	String openid = winnerService.selectAndUpdate(winner, winnerid, request);
    		if(request.getParameter("fromSystem") != null && !request.getParameter("fromSystem").equals("")){
        		return "redirect:"+"/front?openId="+openid+"&fromSystem="+request.getParameter("fromSystem");       
    		} else{
    			return "redirect:"+"/front?openId="+openid;
    		}
        }
        
        return null;
		
	}	
	
	private String getRequestUrl(HttpServletRequest request){
		return request.getRequestURL() + (StringUtils.isEmpty(request.getQueryString()) ? "" : ("?"+request.getQueryString()));
	}
	
	private String getRequestUrl2(HttpServletRequest request){
		return (StringUtils.isEmpty(request.getQueryString()) ? "" : ("?"+request.getQueryString()));
	}	
	
	

	@RequestMapping(value = {"${frontPath}/shareIndex"})	
	public String shareIndex(HttpServletRequest request,HttpServletResponse response, Model model) throws UnsupportedEncodingException{
						
		String shareId = request.getParameter("shareId");
		String openId = request.getParameter("openId");
		
		List<Sharegrid> gridList = sharegridService.getByShareId(shareId);
		model.addAttribute("gridList", gridList);
		model.addAttribute("shareId", shareId);
							
		//回收过期的宫格还有奖品
		sharegridService.recoveryGrid(shareawardService.recoveryAward());
		winnerService.recoveryIntimeAward();
		
		 String fromSystem = request.getParameter("fromSystem");        
		StringBuffer u = request.getRequestURL();  
		String tempContextUrl = u.delete(u.length() - request.getRequestURI().length(), u.length()).append("/").toString();  	
		if(fromSystem != null && fromSystem.equals("mama100")){	
			model.addAttribute("url", "http://"+Global.getConfig("serverurl")+"/f/shareIndex?shareId="+shareId+"&fromSystem=mama100");							
		}				
		else{
			model.addAttribute("url", "http://"+Global.getConfig("serverurl")+"/f/shareIndex?shareId="+shareId);		
		}            
        
		//如果有分享中奖纪录，则跳到详情页
		Winner w =null;
		Share share = shareService.get(shareId);
		if(share != null ){
			 w = winnerService.getByOpenid(share.getCode(), openId);
			if(w != null){		
				model.addAttribute("awardName", w.getAwardname());
				model.addAttribute("sharecode", share.getCode());
				model.addAttribute("moviecode", w.getMovieCode());							
				model.addAttribute("registerUrl", drawService.getRegisterUrl(request,openId));		
				model.addAttribute("expire", "0");
												
				if(w.getMemberId() != 0){
					model.addAttribute("rank", "member");
				}else{
					model.addAttribute("rank", "nonMember");
				}	
					
				if(w.getIsAward() == 1){
										
					//如果中的是电影票
					if(w.getMovieCode() != null && !w.getMovieCode().equals("")){						
						if(w.getIsLimit() == 0){
							
							String requestUrl = request.getRequestURL().toString(); 							
							if(requestUrl.substring(requestUrl.length()-1,requestUrl.length()).equals("/")){
							    requestUrl = requestUrl.substring(0,requestUrl.length()-1);
							}		
							String url =  "http://"+Global.getConfig("serverurl") +"/f/shareIndex"+getRequestUrl2(request);			
							
							
							byte[] sendBytes1 = HttpRequestService.sendGet(BiostimeWechat.Jsticket, "from=ismart");
							byte[] sendBytes2 = HttpRequestService.sendGet(BiostimeWechat.AppID, "from=ismart");
							
							String jsticketJson=new String( sendBytes1 ,"UTF-8"); 
							String appIdJson=new String( sendBytes2 ,"UTF-8"); 							
							
							HashMap<String,String> m = (HashMap<String, String>) BiostimeWechat.Api.toMap(jsticketJson);							
							String jsticket = m.get("jsticket");
							
							m = (HashMap<String, String>) BiostimeWechat.Api.toMap(appIdJson);										
							String appId = m.get("appId");			
														
							HashMap<String,String> map = (HashMap<String, String>) CreateSignService.sign(jsticket, url);
							map.put("appId", appId);
							map.put("url",url);
							model.addAttribute("map", map);			
							model.addAttribute("source", w.getSource());		
							
							if(w.getSource().equals("share")){
								return "modules/front/sharemovie";
							}else{
								return "modules/front/movie2";
							}
							
						}						
					}
					
					//如果中的不是电影票
					else{
						if(w.getIsLimit() == 0){
							return "modules/front/shareAward";
						}
					}
					
				}
			}
			
			/**
			 * 
			 * 中奖后7天或分享后3天分享链接过期，过期后没中奖的用户进入页面提示“来晚了，
			 * 分享已过期”，已中奖的用户依然看到自己的奖品。
			 * 
			 * */
			else{
				
				//判断中奖后7天
				if(share.getCreateDate().getTime() + 604800*1000 < new Date().getTime()){
					model.addAttribute("expire", "1");
				}
				
				//判断分享后3天
				Winner wi = winnerService.getByCodeAndOpenid(share.getCode(), null);
				if(wi != null && (wi.getCreateDate().getTime() + 604800*1000< new Date().getTime())){
					model.addAttribute("expire", "1");
				}
				
			}
		}
		   			
			try {
															        
				//判断是否有openId
				if(openId == null){ 

					//String url = getRequestUrl(request);
					String url = "http://"+Global.getConfig("serverurl")+"/f/shareIndex?shareId="+shareId+"&fromSystem="+fromSystem;
					String authUrl = null;
												
/*					//从妈妈100进来的，附带参数fromSystem=mama100
					if(fromSystem != null && "mama100".equals(fromSystem)){								
						authUrl = "http://"+Global.getConfig("serverurl")+"/bncweixin/service/authorize?encodeTargetUrl="+URLEncoder.encode(url,"utf-8")+
								"&fromSystem=mama100";
					}
					
					//从合生元进来的
					else{
						authUrl = "http://"+Global.getConfig("serverurl")+"/bncweixin/service/authorize?encodeTargetUrl="+URLEncoder.encode(url,"utf-8");
					}*/
					
					authUrl = "http://"+Global.getConfig("biostime.wxhost")+"/bncweixin/service/authorize?encodeTargetUrl="+URLEncoder.encode(url,"utf-8");
																					
					return "redirect:"+authUrl;
				}			
								
				model.addAttribute("openId", openId);
				model.addAttribute("openid", openId);
				model.addAttribute("fromSystem", fromSystem);
			
			} catch (Exception e) {
				e.printStackTrace();
			}
				 
		logger.info("-----------shareId------------"+shareId);
		logger.info("-----------openId------------"+openId);
		logger.info("-----------fromSystem------------"+fromSystem);
		
		return "modules/front/shareIndex";
	}
		
	@RequestMapping(value = {"${frontPath}/shareDraw"})	
	@ResponseBody
	public  ObjResponse<DrawDto> shareDraw(HttpServletRequest request, HttpServletResponse response, Model model){
		int errCode = 0;
		String errMsg = "抽奖成功";
		DrawDto drawDto = null;
		try{
			drawDto = (DrawDto) drawService.shareDraw(request);
		}catch(Exception ex){
			errCode = 1;
			errMsg = ex.getMessage();
			logger.info("--------------出现异常了-----------"); 
		}
		
		ObjResponse<DrawDto> res = FastResponse
				.create()
				.errCode(errCode)
				.errMsg(errMsg)
				.obj(drawDto);		
		
		return res;
	}		

	@RequestMapping(value = {"${frontPath}/bindAward"})	
	public String bindAward(HttpServletRequest request,HttpServletResponse response, Model model){
		
		logger.info("--------------注册后进入回调接口---------------"); 
		
		String shareawardId = request.getParameter("shareawardId");
		String shareId = request.getParameter("shareId");
		String sharegridId = request.getParameter("sharegridId");
		String openId = request.getParameter("openId");
		String sign = request.getParameter("sign");
		String fromSystem = request.getParameter("fromSystem");	
		drawService.bindAward(shareawardId, shareId, sharegridId, openId,sign); 
		
		logger.info(shareawardId);
		logger.info(shareId);
		logger.info(sharegridId);
		logger.info(openId);
		logger.info(sign);
		
		List<Sharegrid> gridList = sharegridService.getByShareId(shareId);
		model.addAttribute("gridList", gridList);
		model.addAttribute("shareId", shareId);
		model.addAttribute("openId", openId);
		model.addAttribute("fromSystem", fromSystem);
				
		return "redirect:"+"/f/shareIndex";
		
	}	
	
	@RequestMapping(value = {"${frontPath}/getMyAwards"})
	public String getMyAwards(HttpServletRequest request, HttpServletResponse response, Model model) {
		String openId = request.getParameter("openId");
		String fromSystem = request.getParameter("fromSystem");
		List<WinnerDto>  dtoList = winnerService.getMyAwards(openId);
		model.addAttribute("dtoList", dtoList);
		model.addAttribute("openId", openId);
		model.addAttribute("fromSystem", fromSystem);
		return "modules/front/myself";
	}
		
	@RequestMapping(value ="jssdkConifg")	
	public String jssdkConifg(HttpServletRequest request, HttpServletResponse response, Model model){			
		HashMap<String,Object> map = jssdkService.jssdk(request);		
		model.addAttribute("map", map);		
		return "modules/front/demo";
	}	
			
}
